using System;
using System.Web.Routing;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using SoftwareMonkeys.Scriptech.Diagnostics;

namespace SoftwareMonkeys.Scriptech.Scripts
{
	public class ScriptRouteHandler : IRouteHandler
	{
		public string ScriptName = String.Empty;

		public ScriptRouteHandler (string virtualPath)
		{
			this.VirtualPath = virtualPath;
		}

		public ScriptRouteHandler ()
		{
			Initialize();
		}
		
		public void Initialize()
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Initializing script route handler."))
			{
				ScriptName = GetScriptName ();
				string scriptNameFixed = ScriptName;
				
				LogWriter.Debug("Script name: " + ScriptName);
				
				// The path gets used in a query string so the ? character needs to be replaced with & otherwise the path will end up with two ? characters
				scriptNameFixed = scriptNameFixed.Replace("?", "&");
				
				LogWriter.Debug("Script name (fixed): " + scriptNameFixed);
				
				if (scriptNameFixed != String.Empty) {
					
					string launchFile = "LaunchScript.aspx";
					if (HttpContext.Current.Request.QueryString["Raw"] != null && HttpContext.Current.Request.QueryString["Raw"].ToLower() == "true")
						launchFile = "LaunchScriptRaw.aspx";
					
					LogWriter.Debug("Launch file: " + launchFile);
					
					VirtualPath = HttpContext.Current.Request.ApplicationPath + "/" + launchFile + "?Script=" + scriptNameFixed;
					
					LogWriter.Debug("Virtual path: " + VirtualPath);
				}
				else
					LogWriter.Debug("No script detected. Skipping routing.");
			}
		}

		public string GetScriptName ()
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Retrieving the current script name"))
			{
				string scriptName = Scripts.GetCurrentScript(true);
				
				LogWriter.Debug("Script name: " + scriptName);
				
				return scriptName;
				
				// TODO: Clean up
				
			/*string url = HttpContext.Current.Request.Url.ToString ();
			
			string baseUrl = new UrlMapper().MapUrl("/Scripts") + "/";
			
			string script = url.Replace (baseUrl, "");
			
			
			// If prepared properly then return the script
			if (script != String.Empty && script.IndexOf (":") == -1) {
				return script;
			} else
				// Otherwise no script was detected
				return String.Empty;*/
			}
		}

		public string VirtualPath { get; private set; }

		public IHttpHandler GetHttpHandler (RequestContext requestContext)
		{
			Initialize();
			
			// TODO: Check which one is needed.
			//return new AsyncScriptHttpHandler (this.VirtualPath);
			return new ScriptHttpHandler(this);
			//IHttpHandler page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler;
			//page.
			//return page;
			
		}
	}
}

